package com.sun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.Result;
import com.sun.common.SystemCrmlog;
import com.sun.dto.PurchaseDto;
import com.sun.entity.Drug;
import com.sun.entity.Sale;
import com.sun.entity.Store;
import com.sun.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/22 12:44
 * @FileName: PurchaseController
 * @Description: ""
 */
@RestController
@RequestMapping("/purchase")
public class PurchaseController {


    @Autowired
    private DrugService drugService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private SaleService saleService;
    @Autowired
    private PurchaseHeadService purchaseHeadService;
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    /**
     * 查询库存小于库存下限的药品
     *
     * @return
     */
    @GetMapping("/inventoryQuery")
    public Result<List<Store>> inventoryQuery() {
        List<Store> result = new ArrayList<>();
        List<Drug> drugList = drugService.list();
        for (Drug drug : drugList) {
            Store store = new Store();
            LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Store::getDrugId, drug.getDrugId());
            List<Store> stores = storeService.list(lambdaQueryWrapper);
            if (stores.isEmpty()) {
                store.setDrugId(drug.getDrugId());
                store.setDrugName(drug.getDrugName());
                store.setDrugCode(drug.getDrugCode());
                store.setDrugNumber(0);
            } else {
                int num = 0;
                for (int i = 0; i < stores.size(); i++) {
                    num = num + stores.get(i).getDrugNumber();
                }
                if (num < drug.getLowerlimit()) {
                    store.setDrugId(drug.getDrugId());
                    store.setDrugName(drug.getDrugName());
                    store.setDrugCode(drug.getDrugCode());
                    store.setDrugNumber(num);
                }
            }
            result.add(store);
        }
        return Result.success(result);
    }

    /**
     * 查询销售排名前20的药品    未测试和完善  有点问题
     *
     * @return
     */
    @GetMapping("/salesRankQuery")
    public Result<List<Sale>> salesRankQuery() {
        LambdaQueryWrapper<Sale> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Sale::getNum);
        lambdaQueryWrapper.last("LIMIT 20");
        List<Sale> sales = saleService.list(lambdaQueryWrapper);
        return Result.success(sales);
    }

    /**
     * 采购单信息分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param userName
     * @param supplierName
     * @return
     */
    @GetMapping("/page")
    public Result<IPage> page(int pageNum, int pageSize, String userName, String supplierName, Integer status,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<PurchaseDto> pageInfo = new Page<>(pageNum, pageSize);

        IPage<PurchaseDto> purchaseDtoPage = purchaseHeadService.selectPurchaseDtoListPage(pageInfo, userName, supplierName, status, startTime, endTime);

        return Result.success(purchaseDtoPage);
    }

    /**
     * 新增采购计划
     *
     * @return
     */
    @SystemCrmlog(title = "采购管理模块", type = "INSERT", description = "新增采购计划")
    @PostMapping
    public Result<String> save(@RequestBody PurchaseDto purchaseDto) {
        purchaseHeadService.saveWithPurchaseDetail(purchaseDto);
        return Result.success("新增采购计划成功");
    }

    /**
     * 根据id查询采购单和对应的药品信息
     *
     * @return
     */
    @GetMapping("/{id}")
    public Result<PurchaseDto> get(@PathVariable Long id) {
        PurchaseDto purchaseDto = purchaseHeadService.getByIdWithPurchaseDetail(id);
        return Result.success(purchaseDto);
    }

    /**
     * 更新采购单，同时更新对应的药品信息
     *
     * @return
     */
    @SystemCrmlog(title = "采购管理模块", type = "UPDATE", description = "更新采购单")
    @PutMapping
    public Result<String> update(@RequestBody PurchaseDto purchaseDto) {

        purchaseHeadService.updateWithPurchaseDetail(purchaseDto);

        return Result.success("采购单信息修改成功");
    }

    /**
     * 根据id删除采购单
     *
     * @return
     */
    @SystemCrmlog(title = "采购管理模块", type = "DELETE", description = "根据id删除采购单")
    @DeleteMapping("/{ids}")
    public Result<String> batchDelete(@PathVariable Long ids) {
        purchaseHeadService.batchDeleteByIds(Collections.singletonList(ids));
        return Result.success("成功删除采购单！");
    }

    /**
     * 修改采购单状态
     */
    @SystemCrmlog(title = "采购管理模块", type = "UPDATE", description = "修改采购单状态")
    @PostMapping("/status/{status}/{ids}")
    public Result<String> updateStatus(@PathVariable Integer status, @PathVariable Long ids) {
        purchaseHeadService.updateStatusByIds(status, Collections.singletonList(ids));

        return Result.success("采购单状态已更改!");
    }

}
